package com.eshop.tools.service.impl;

import java.lang.invoke.SerializedLambda;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import java.io.Serializable;
import com.qiniu.http.Response;
import com.alibaba.fastjson.JSON;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.Configuration;
import com.eshop.tools.utils.QiNiuUtil;
import com.eshop.utils.FileUtil;
import org.springframework.web.multipart.MultipartFile;
import com.eshop.exception.BadRequestException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.tools.domain.QiniuConfig;
import com.eshop.tools.domain.QiniuContent;
import java.util.List;
import org.springframework.data.domain.Pageable;
import com.eshop.tools.service.dto.QiniuQueryCriteria;
import org.springframework.beans.factory.annotation.Value;
import com.eshop.dozer.service.IGenerator;
import com.eshop.tools.service.QiniuContentService;
import com.eshop.tools.service.QiniuConfigService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.tools.service.QiNiuService;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class QiNiuServiceImpl implements QiNiuService
{
    private final QiniuConfigService qiniuConfigService;
    private final QiniuContentService qiniuContentService;
    private final IGenerator generator;
    @Value("${qiniu.max-size}")
    private Long maxSize;
    
    public QiNiuServiceImpl(final QiniuConfigService qiniuConfigService, final QiniuContentService qiniuContentService, final IGenerator generator) {
        this.qiniuConfigService = qiniuConfigService;
        this.qiniuContentService = qiniuContentService;
        this.generator = generator;
    }
    
    @Override
    public Object queryAll(final QiniuQueryCriteria criteria, final Pageable pageable) {
        return this.qiniuContentService.queryAll(criteria, pageable);
    }
    
    @Override
    public List<QiniuContent> queryAll(final QiniuQueryCriteria criteria) {
        return this.qiniuContentService.queryAll(criteria);
    }
    
    @Override
    public QiniuConfig find() {
        final QiniuConfig qiniuConfig = (QiniuConfig)this.qiniuConfigService.getOne((Wrapper)(Wrappers.<QiniuConfig>lambdaQuery().orderByAsc(QiniuConfig::getId)).last("limit 1"));
        return qiniuConfig;
    }
    
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public QiniuConfig update(final QiniuConfig qiniuConfig) {
        final String http = "http://";
        final String https = "https://";
        if (!qiniuConfig.getHost().toLowerCase().startsWith(http) && !qiniuConfig.getHost().toLowerCase().startsWith(https)) {
            throw new BadRequestException("外链域名必须以http://或者https://开头");
        }
        qiniuConfig.setId(1L);
        this.qiniuConfigService.saveOrUpdate(qiniuConfig);
        return qiniuConfig;
    }
    
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public QiniuContent upload(final MultipartFile file, final QiniuConfig qiniuConfig) {
        FileUtil.checkSize((long)this.maxSize, file.getSize());
        if (qiniuConfig.getId() == null) {
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        final Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
        final UploadManager uploadManager = new UploadManager(cfg);
        final Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        final String upToken = auth.uploadToken(qiniuConfig.getBucket());
        try {
            String key = file.getOriginalFilename();
            if (this.qiniuContentService.getOne((Wrapper)Wrappers.<QiniuContent>lambdaQuery().eq(QiniuContent::getName, key)) != null) {
                key = QiNiuUtil.getKey(key);
            }
            final Response response = uploadManager.put(file.getBytes(), key, upToken);
            final DefaultPutRet putRet = (DefaultPutRet)JSON.parseObject(response.bodyString(), (Class)DefaultPutRet.class);
            final QiniuContent content = (QiniuContent)this.qiniuContentService.getOne(Wrappers.<QiniuContent>lambdaQuery().eq(QiniuContent::getName, FileUtil.getFileNameNoEx(putRet.key)));
            if (content == null) {
                final QiniuContent qiniuContent = new QiniuContent();
                qiniuContent.setSuffix(FileUtil.getExtensionName(putRet.key));
                qiniuContent.setBucket(qiniuConfig.getBucket());
                qiniuContent.setType(qiniuConfig.getType());
                qiniuContent.setName(FileUtil.getFileNameNoEx(putRet.key));
                qiniuContent.setUrl(qiniuConfig.getHost() + "/" + putRet.key);
                qiniuContent.setSize(FileUtil.getSize((long)Integer.parseInt(file.getSize() + "")));
                this.qiniuContentService.save(qiniuContent);
                return qiniuContent;
            }
            return content;
        }
        catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    
    @Override
    public QiniuContent findByContentId(final Long id) {
        final QiniuContent qiniuContent = (QiniuContent)this.qiniuContentService.getById((Serializable)id);
        return qiniuContent;
    }
    
    @Override
    public String download(final QiniuContent content, final QiniuConfig config) {
        final String type = "公开";
        String finalUrl;
        if (type.equals(content.getType())) {
            finalUrl = content.getUrl();
        }
        else {
            final Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
            final long expireInSeconds = 3600L;
            finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
        }
        return finalUrl;
    }
    
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public void delete(final QiniuContent content, final QiniuConfig config) {
        final Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        final Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        final BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getName() + "." + content.getSuffix());
            this.qiniuContentService.removeById((Serializable)content.getId());
        }
        catch (QiniuException ex) {
            this.qiniuConfigService.removeById((Serializable)content.getId());
        }
    }
    
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public void synchronize(final QiniuConfig config) {
        if (config.getId() == null) {
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        final Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        final Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        final BucketManager bucketManager = new BucketManager(auth, cfg);
        final String prefix = "";
        final int limit = 1000;
        final String delimiter = "";
        final BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            final FileInfo[] next;
            final FileInfo[] items = next = fileListIterator.next();
            for (final FileInfo item : next) {
                if (this.qiniuContentService.getOne((Wrapper)Wrappers.<QiniuContent>lambdaQuery().eq(QiniuContent::getName, FileUtil.getFileNameNoEx(item.key))) == null) {
                    final QiniuContent qiniuContent = new QiniuContent();
                    qiniuContent.setSize(FileUtil.getSize((long)Integer.parseInt(item.fsize + "")));
                    qiniuContent.setSuffix(FileUtil.getExtensionName(item.key));
                    qiniuContent.setName(FileUtil.getFileNameNoEx(item.key));
                    qiniuContent.setType(config.getType());
                    qiniuContent.setBucket(config.getBucket());
                    qiniuContent.setUrl(config.getHost() + "/" + item.key);
                    this.qiniuContentService.save(qiniuContent);
                }
            }
        }
    }
    
    @Override
    public void deleteAll(final Long[] ids, final QiniuConfig config) {
        for (final Long id : ids) {
            this.delete(this.findByContentId(id), config);
        }
    }
    
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public void update(final String type) {
        this.qiniuConfigService.update(type);
    }
    
    @Override
    public void downloadList(final List<QiniuContent> queryAll, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final QiniuContent content : queryAll) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("文件名", content.getName());
            map.put("文件类型", content.getSuffix());
            map.put("空间名称", content.getBucket());
            map.put("文件大小", content.getSize());
            map.put("空间类型", content.getType());
            map.put("创建日期", content.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
}
